package com.cl.code.web.config;

import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import com.cl.code.web.component.filter.WebLogFilter;
import jakarta.servlet.Filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.context.support.StandardServletEnvironment;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

/**
 * @author chengliang
 * @since 1.0.0
 */
@Slf4j
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 配置自定义的HttpMessageConverters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("Initializing FastJsonHttpMessageConverter");
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        // 设置FastJson的配置
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        // 序列化特性
        fastJsonConfig.setWriterFeatures(
                JSONWriter.Feature.BrowserCompatible,
                JSONWriter.Feature.WriteNulls,
                JSONWriter.Feature.WriteNullListAsEmpty,
                JSONWriter.Feature.WriteMapNullValue
        );

        converter.setFastJsonConfig(fastJsonConfig);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        // 设置支持的媒体类型
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
        converters.addFirst(converter);
    }


    @Bean
    @ConditionalOnClass({StandardServletEnvironment.class})
    public FilterRegistrationBean<Filter> logFilter() {
        log.info("Initializing WebLogFilter");
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new WebLogFilter());
        registrationBean.setOrder(Integer.MAX_VALUE);
        return registrationBean;
    }

}
